package CSR_V3;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

class BilleterieImpl implements Billeterie {

	private int nbTickets = 10;

	public void reservation(int nb) throws RemoteException {
		Reserveur r = new Reserveur(this, nb);
		r.start();

		try {
			r.join();
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}
	}

	public synchronized void ajouterTickets(int nb) {
		nbTickets += nb;
		System.out.println(nb + " tickets ajoutes.");
		System.out.println("*** Reste " + nbTickets + " tickets.");
		notifyAll();
	}

	public synchronized void acheter(int nb) {
		while (nbTickets < nb) {
			try {
				wait();
			} catch (InterruptedException ie) {
				ie.printStackTrace();
			}
		}
		nbTickets -= nb;
		System.out.println("*** " + Thread.currentThread().getName()
				+ " a achete " + nb + " tickets.");
		System.out.println("*** Reste " + nbTickets + " tickets.");
	}

	public static void main(String args[]) {
		Billeterie b = new BilleterieImpl();

		try {

			System.out.print("Installing security manager...");
			if (System.getSecurityManager() == null) {
				System.setSecurityManager(new SecurityManager());
			}
			System.out.println("done.");

			System.out.println("Creating and registering the stub...");
			Billeterie stub = (Billeterie) UnicastRemoteObject.exportObject(b,
					0);
			Registry registry = LocateRegistry.getRegistry();
			registry.rebind("sncf", stub);
			System.out.println("done.");

		} catch (Exception re) {
			re.printStackTrace();
		}

	}

} // BilleterieImpl